<?php
/**
 * Created by PhpStorm.
 * User: 王松
 * Time: 2017/7/19 11:19
 */

namespace App\Models\Observer;

use App\Models\DoctorDetail;
use GuzzleHttp\Client;
use Illuminate\Database\Eloquent\Model;

class UserObserver extends ModelObserverAbstract
{
    public function saved(Model $user)
    {
        //  清除缓存
        $this->removeCache($user);
    }

    public function created(Model $user)
    {
        $user->createtime = $user->created_at->timestamp;
        $user->DEVICET = 4;

        $user->save();

        $this->relation($user);
        $this->createHx($user, true);
    }

    public function createHx(Model $user, $isDoctor = false)
    {
        if (!env('APP_DEBUG')) {
            return;
        }

        $url = 'http://www.365tang.cn/h5/registerhx?';
        $param = [
            'ACCOUNT' => $user->account
        ];
        if (true === $isDoctor) {
            $param['DOCTOR'] = 1;
        }
        $url .= http_build_query($param);
        $client = new Client();
        $client->get($url);
    }

    public function relation(Model $user)
    {
        $insert = array_merge(
            ['account' => $user->account],
            $this->request->input()
        );

        DoctorDetail::create($insert);
    }

    public function deleted(Model $user)
    {
        //  清除缓存
        $this->removeCache($user);

        //  清除用户角色
        $user->roles()->select('name')->get()->map(function ($role) use($user) {
            $user->retract($role->name);
        });

        //  清除权限缓存
        \Bouncer::refreshFor($user);

        DoctorDetail::where('account', $user->account)->delete();
    }
}